判断一个对象是否有某属性, 可以通过key in obj或者obj.hasOwnProperty(key)来判断, 那么它们有什么区别呐

Object.prototype.hasOwnProperty()只判断对象自身属性中是否具有指定的属性

in不止会判断对象自身属性, 还包括原形链上的属性

比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const foo = []

foo.bar = undefined

console.log('push' in foo)
//true

console.log(foo.hasOwnProperty('push'))
//false

console.log('bar' in foo)
//true

console.log(foo.hasOwnProperty('bar'))
//true

常见的, 会在为对象循环赋值时通过Object.prototype.hasOwnProperty()判断是否是对象原型链上的属性, 用来防止误修改原型链上的属性